package com.atguigu.gmall.juc.atomic;

import java.util.HashMap;
import java.util.HashSet;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author 陈昆昆
 * @version 1.0
 * @date 2020/6/2 15:56
 */
public class WriteReadTest {
    private volatile HashMap<String,String> map = new HashMap<>();
    private ReentrantReadWriteLock writeLock = new ReentrantReadWriteLock();
    public void putkey(String key){
        writeLock.writeLock().lock();
        try{
            System.out.println(Thread.currentThread().getName()+"正在写入");
            map.put(key,Thread.currentThread().getName());
            try { Thread.sleep(1); } catch (InterruptedException e) { e.printStackTrace();}
            System.out.println(Thread.currentThread().getName() + "写入完成");
        }finally {
            writeLock.writeLock().unlock();
        }
    }

    public void getkey(String key){
        writeLock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "正在读取");
            String result = map.get(key);
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "读取完成" + result);
        }finally {
            writeLock.readLock().unlock();
        }
    }


    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) {
            new Thread(()->{
                WriteReadTest writeReadTest = new WriteReadTest();
                writeReadTest.putkey(Thread.currentThread().getName());
                writeReadTest.getkey(Thread.currentThread().getName());
            },String.valueOf(i)).start();
        }
    }
}
